const elements = require('./elements');
//const __placeImgeUrlHttps = "https";
//const __emojisReg = '';
//const __emojisBaseSrc = '';
//const __emojis = {};
const wxDiscode = require('./wxDiscode');
const HTMLParser = require('./htmlparser');

function removeDOCTYPE(html) {
  return html
    .replace(/<\?xml.*\?>\n/, '')
    .replace(/<.*!doctype.*\>\n/, '')
    .replace(/<.*!DOCTYPE.*\>\n/, '');
}

function trimHtml(html) {
  return html
    .replace(/\r?\n+/g, '')
    .replace(/<!--.*?-->/ig, '')
    .replace(/\/\*.*?\*\//ig, '')
    .replace(/[ ]+</ig, '<')
}

/**
 * 将html内容转换为json格式
 */
function html2json(html, bindName) {
  //处理字符串
  html = removeDOCTYPE(html);
  html = trimHtml(html);
  //html = wxDiscode.strDiscode(html);
  //生成node节点
  let bufArray = [];
  let results = {
    node: bindName,
    nodes: [],
    images: [],
    imageUrls: []
  };
  /**
   *将节点放置到父节点
   *@param node 当前的node节点
   */
  function pushNode2ParentNodeList(node) {
    if (bufArray.length === 0) {
      node.index = index.toString();
      index += 1;
      results.nodes.push(node);
    } else {
      let parent = bufArray[0];
      if (parent.nodes === undefined) {
        parent.nodes = [];
      }
      node.parent = parent.tag;
      node.index = parent.index + '.' + parent.nodes.length;
      parent.nodes.push(node);
    }
  }
  let index = 0;
  HTMLParser(html, {
    /**
     *处理开始标签，
     *@param tag 标签名称
     *@param attrs 标签属性
     *@param unary	是否闭合标签
     */
    start: function(tag, attrs, unary) {
      let node = {
        node: 'element',
        tag: tag,
      };
      if (bufArray.length === 0) {
        node.index = index.toString()
        index += 1;
      } else {
        let parent = bufArray[0];
        if (parent.nodes === undefined) {
          parent.nodes = [];
        }
        node.index = parent.index + '.' + parent.nodes.length
      }

      if (elements.block[tag]) {
        node.tagType = "block";
      } else if (elements.inline[tag]) {
        node.tagType = "inline";
      } else if (elements.closeSelf[tag]) {
        node.tagType = "closeSelf";
      }
      if (attrs.length !== 0) {
        node.attr = attrs.reduce(function(pre, attr) {
          let name = attr.name;
          let value = attr.value;
          if (name == 'class') {
            node.classStr = value;
          }
          // has multi attibutes
          // make it array of attribute
          if (name == 'style') {
            node.styleStr = value;
          }
          //src，href属性不去split，否则可能会变成数组类型
          if (name !=='src' && name !=='href' && value.match(/ /)) {
            value = value.split(' ');
          }
          // if attr already exists
          // merge it
          if (pre[name]) {
            if (Array.isArray(pre[name])) {
              // already array, push to last
              pre[name].push(value);
            } else {
              // single value, make it array
              pre[name] = [pre[name], value];
            }
          } else {
            // not exist, put it
            pre[name] = value;
          }
          return pre;
        }, {});
      }

      //对img添加额外数据
      if (node.tag === 'img' && node.attr.src ) {
            node.imgIndex = results.images.length;
            let imgUrl = node.attr.src.trim().replace(/tp=webp/ig,"");
            node.attr.src = imgUrl;
            node.from = bindName;
            results.images.push(node);
            results.imageUrls.push(imgUrl);
      }
      // 处理font标签样式属性
      else if (node.tag === 'font') {
        let fontSize = ['x-small', 'small', 'medium', 'large', 'x-large', 'xx-large', '-webkit-xxx-large'];
        let styleAttrs = {
          'color': 'color',
          'face': 'font-family',
          'size': 'font-size'
        };
        if (!node.attr.style) node.attr.style = [];
        if (!node.styleStr) node.styleStr = '';
        for (let key in styleAttrs) {
          if (node.attr[key]) {
            let value = key === 'size' ? fontSize[node.attr[key] - 1] : node.attr[key];
            node.attr.style.push(styleAttrs[key]);
            node.attr.style.push(value);
            node.styleStr += styleAttrs[key] + ': ' + value + ';';
          }
        }
      } else if (node.tag === 'video' || node.tag === 'audio') {
        node.attr.controls = !node.attr.controls ? false : true;
        node.attr.autoplay = !node.attr.autoplay ? false : true;
        node.attr.loop = !node.attr.loop ? false : true;
        if (node.tag === 'video') {
          node.attr.muted = !node.attr.muted ? false : true;
        } else {
          let params = node.attr['data-extra'];
          if (params) {
            params = params.replace(new RegExp('&quot;', 'g'), '"');
            params = JSON.parse(params);
            node.attr.poster = params.poster;
            node.attr.name = params.name;
            node.attr.author = params.author;
          }
        }
      }else if(node.tag == 'ul' || node.tag =='ol'){
          node.order = 0;
      }else if(node.tag == 'li'){
          //计算li的数量
          let parent = bufArray[0] || results;
          if(parent && (parent.tag == 'ul' || parent.tag == 'ol')){
            parent.order = parent.order + 1;
            node.order = parent.order;
          }
      }
      if (unary) {
        if (typeof node.attr === 'object' ) {
          if (node.attr.style instanceof Array){
            delete node.attr.style;
          }
          if(node.attr["class"] instanceof Array){
            delete node.attr["class"];
          } 
        }
        let parent = bufArray[0] || results;
        if (parent.nodes === undefined) {
          parent.nodes = [];
        }
        node.parent = parent.tag;
        parent.nodes.push(node);
      } else {
        bufArray.unshift(node);
      }
    },
    /**
     *	处理结束标签
     */
    end: function(tag) {
      // merge into parent tag
      let node = bufArray.shift(); //去除缓冲区的第一个未关闭标签
      if (node.tag !== tag)
        console.error('invalid state: mismatch end tag');
      /**
       * 处理视频和音频
       */
      if (node.tag === 'video' || node.tag === 'audio') {
        if (!node.attr.src) {
          let nodes = node.nodes;
          if (nodes instanceof Array && nodes.length > 0) {
            for (let i = 0; i < nodes.length; i++) {
              if (nodes[i].tag === 'source' && nodes[i].attr.src) {
                node.attr.src = nodes[i].attr.src;
                break;
              }
            }
          }
          delete node.nodes; //删掉音频视频的nodes节点
        }
      }
      if (typeof node.attr === 'object') {
        if (node.attr.style instanceof Array) {
          delete node.attr.style;
        }
        if (node.attr["class"] instanceof Array) {
          delete node.attr["class"];
        }
      }
      pushNode2ParentNodeList(node);
    },
    /**
     *	处理文本标签
     *
     */
    chars: function(text) {
      //debug(text);
      let node = {
        node: 'text',
        text: wxDiscode.strDiscode(text)
        /*,textArray:transEmojiStr(text)*/
      };
      pushNode2ParentNodeList(node);
    },
    comment: function(text) {

    },
  });
  return results;
};

/*function transEmojiStr(str){

  let emojiObjs = [];
  if(__emojisReg.length == 0 || !__emojis){
      let emojiObj = {}
      emojiObj.node = "text";
      emojiObj.text = str;
      array = [emojiObj];
      return array;
  }
  //这个地方需要调整
  str = str.replace(/\[([^\[\]]+)\]/g,':$1:')
  let eReg = new RegExp("[:]");
  let array = str.split(eReg);
  for(let i = 0; i < array.length; i++){
    let ele = array[i];
    let emojiObj = {};
    if(__emojis[ele]){
      emojiObj.node = "element";
      emojiObj.tag = "emoji";
      emojiObj.text = __emojis[ele];
      emojiObj.baseSrc= __emojisBaseSrc;
    }else{
      emojiObj.node = "text";
      emojiObj.text = ele;
    }
    emojiObjs.push(emojiObj);
  }
  
  return emojiObjs;
}*/

//function emojisInit(reg='',baseSrc="/wxParse/emojis/",emojis){
//  __emojisReg = reg;
//  __emojisBaseSrc=baseSrc;
//  __emojis=emojis;
//}

module.exports = {
  html2json: html2json
  /*,emojisInit:emojisInit*/
};